import type { PaginationProps } from '../types/pagination';
import type { BasicTableProps } from '../types/table';
import { computed, unref, ref, ComputedRef } from 'vue';

import { isBoolean } from '@/utils/is';
import { APISETTING, DEFAULTPAGESIZE, PAGESIZES } from '../const';

import i18n from '@/i18n';

export function usePagination(refProps: ComputedRef<BasicTableProps>) {
  const configRef = ref<PaginationProps>({});
  const show = ref(true);

  const getPaginationInfo = computed((): PaginationProps | boolean => {
    const { pagination } = unref(refProps);
    if (!unref(show) || (isBoolean(pagination) && !pagination)) {
      return false;
    }
    const { totalField } = APISETTING;

    const { locale } = i18n.global;

    const showQuickJumper = unref(configRef)[totalField] / (unref(configRef)['pageSize'] || 0) > 5;

    const obj: any = {
      pageSize: DEFAULTPAGESIZE,
      pageSizes: PAGESIZES,
      showSizePicker: true,

      ...(isBoolean(pagination) ? {} : pagination),
      ...unref(configRef),
      pageCount: unref(configRef)[totalField],
      prefix() {
        const total = unref(configRef)[totalField];

        return total
          ? locale.value === 'en'
            ? `Total ${unref(configRef)[totalField]}`
            : `共 ${unref(configRef)[totalField]} 条`
          : null;
      },
      showQuickJumper,
    };

    const { total = null, pageSize = 10 } = obj;

    if (total !== undefined && pageSize) {
      obj['pageCount'] = Math.ceil(Number(total) / Number(pageSize));
    }

    return obj;
  });

  function setPagination(info: Partial<PaginationProps>) {
    const paginationInfo = unref(getPaginationInfo);
    configRef.value = {
      ...(!isBoolean(paginationInfo) ? paginationInfo : {}),
      ...info,
    };

    // console.log(configRef.value);
  }

  function getPagination() {
    return unref(getPaginationInfo);
  }

  function getShowPagination() {
    return unref(show);
  }

  async function setShowPagination(flag: boolean) {
    show.value = flag;
  }

  return { getPagination, getPaginationInfo, setShowPagination, getShowPagination, setPagination };
}
